<template>
  <el-upload
    :before-upload="beforeAvatarUpload"
    :http-request="customUpload"
    :show-file-list="false"
    action=""
    class="avatar-uploader"
  >
    <img v-if="value" :src="value" alt="" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
// import COS from 'cos-js-sdk-v5'

export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const imageType = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp']
      const isJPG = imageType.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG JPEG PNG GIF BMP 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
/*    customUpload(params) {
      const cos = new COS({
        SecretId: 'AKIDk14uc5JGxObYExe6IEuKUO3UnrfDUVGK', // 应用标识
        SecretKey: 'tVszqRntjJejBNJ2WkjTxDF2bx4wb2FD' // 应用密钥
      })
      cos.putObject({
        Bucket: 'mqgz-1327570948', // 存储桶名称
        Region: 'ap-nanjing', // 存储桶地域
        Key: params.file.name, // 文件名称
        StorageClass: 'STANDARD',
        Body: params.file // 文件对象
      }, (err, data) => {
        // error返回错误信息， data返回数据
        if (data.statusCode === 200 && data.Location) {
          this.$emit('input', `http://${data.Location}`)
        } else {
          this.$message.error(err.message)
        }
      })
    }*/
  }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
